import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { PageQuery } from "src/common/page/PageQuery";
import { GoodsDto } from "src/dto/GoodsDto";
import { GoodsPrice } from "src/entity/GoodsPrice";
import { Unit } from "src/entity/Unit";
import { Repository } from "typeorm";

@Injectable()
export class GoodsPriceService {
    
    @InjectRepository(GoodsPrice)
    private goodsPriceRepository: Repository<GoodsPrice>;

    @InjectRepository(Unit)
    private unitRepository: Repository<Unit>;

    /**
     * 商品价格列表查询
     * @param dto 
     */
    selectGoodsPrice(query: PageQuery<GoodsDto>) {
        if (!query) {
            query = new PageQuery();
        }
        let param = query.param
        let queryBuilder = this.goodsPriceRepository.createQueryBuilder("gp")
        .leftJoinAndSelect("gp.goods", "g");
        if (param?.goodsCode) {
            queryBuilder.andWhere(`g.goods_code like '%${param.goodsCode}%'`);
        }
        if (param?.goodsName) {
            queryBuilder.andWhere(`g.goods_name like '%${param.goodsName}%' 
            or g.niki like '%${param.goodsName}%'
            or FIND_IN_SET(${param.goodsName}, g.niki)
            `)
        }
        // if (param?.)

        return PageQuery.getManyAndCount(query, queryBuilder);
        
    }


    async selectUnitPrice(query: GoodsDto) {
    //    let data = await this.goodsPriceRepository.createQueryBuilder("gp")
    //     .select([
    //         "u.unit_id as unitId",
    //         "u.unit as unit",
    //         "g.goods_code as goodsCode",
    //         "IFNULL(gp.price, 0) as price"
    //     ])
    //     .leftJoin("goods", "g", "g.id = gp.goods_id")
    //     .leftJoin("unit", "u", "gp.unit_id = u.unit_id")
    //     .getRawOne();

    let data = this.unitRepository.query(`
    select
        u.unit_id as unitId,
        g.goods_code as goodsCode,
        IFNULL(gp.price,0) as price,
        g.goods_name goodsName,
        u.unit unit
    from unit as u
    left join goods_price as gp on (u.unit_id = gp.unit_id and gp.goods_id = ${query.id})
    left join goods as g on gp.goods_id = g.id
    `);
        return data;
    }
}